package controllers

import (
	XML "encoding/xml"
	"fmt"
	"lsis/models"
	"strconv"

	"github.com/astaxie/beego"
)

type result struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
}

type resultMsg struct {
	Code    int         `json:"code"`
	Message string      `json:"message"`
	Result  interface{} `json:"result"`
}

type BaseController struct {
	beego.Controller
	user    *models.User
	session *models.Session
}

func (this *BaseController) returnResult(retCode int, msg string, res interface{}) {
	var resp resultMsg

	resp.Code = retCode
	resp.Message = msg
	resp.Result = res

	this.Data["json"] = &resp
	this.ServeJSON()
}

func (this *BaseController) stopRun(errCode int, err error) {
	var resp resultMsg

	resp.Code = errCode
	resp.Message = err.Error()

	this.Data["json"] = &resp
	this.ServeJSON()
	this.StopRun()
}

func (this *BaseController) Prepare() {
	var err error
	ss := this.GetString("session")

	this.session, err = models.GetOpenIdBySession(ss)
	if nil != err {
		beego.Error("get session failed:", err)
		this.stopRun(errCodeGetSession, err)
		return
	}

	this.user, err = models.GetUserByOpenId(this.session.OpenId)
	if err != nil {
		beego.Error("get user failed:", err)
		this.stopRun(errCodeGetUser, err)
		return
	}
}

type MainPageController struct {
	beego.Controller
}

func (s *MainPageController) URLMapping() {
	s.Mapping("defautPage", s.DefautPage)
	s.Mapping("payCallback", s.PaymentCallback)
	s.Mapping("code2session", s.Code2Session)
}

type banner struct {
	Img string `json:"imgUrl"`
	Url string `json:"url"`
}

type location struct {
	Longitude string `json:"longitude"`
	Latitude  string `json:"latitude"`
}

type store struct {
	Name     string   `json:"storeName"`
	Addr     string   `json:"storeAddr"`
	Location location `json:"location"`
}

type report struct {
	Title   string `json:"title"`
	Url     string `json:"url"`
	Img     string `json:"imgUrl"`
	Content string `json:"content"`
}

type defaultPage struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
	Title   string `json:"title"`
	Store   store  `json:"store"`
	Banner  banner `json:"banner"`
	Report  report `json:"report"`
}

// @Title 首页接口
// @Description 获取首页信息
// @Param   location   formData   string  true       "用户当前坐标,如:22.676114,113.9048777"
// @Success 200 {object}  controllers.defaultPage    true      ""
// @Failure 400
// @Failure 404
// @router /defautPage [get]
func (s *MainPageController) DefautPage() {

	var resp defaultPage

	resp.Title = "每天都要美美的你"

	resp.Report.Img = "https://lsis-1256032699.cos.ap-guangzhou.myqcloud.com/%E5%88%87%E7%89%87.png"
	resp.Report.Content = "i-hea，互联网美妆平台，专注服务于白领精英"
	resp.Report.Title = "用美·说爱"

	resp.Banner.Img = "https://lsis-1256032699.cos.ap-guangzhou.myqcloud.com/index-home.png"

	resp.Store.Addr = "壹方城L-001号铺"
	resp.Store.Location.Latitude = "22.553750"
	resp.Store.Location.Longitude = "113.887320"
	resp.Store.Name = "壹方城工作室"

	resp.Code = 0
	resp.Message = "success"

	s.Data["json"] = &resp
	s.ServeJSON()
}

// @Title 获取session
// @Description 用户微信code换取session，role取值：customer,staff（美妆师）,manager
// @Param   code       formData   string  true        "用户code"
// @Param   nickname   formData   string  false       "用户昵称"
// @Param   icon       formData   string  false       "用户头像URL"
// @Success 200 {object} controllers.resonpMsg
// @Failure 400
// @Failure 404
// @router /code2session [post]
func (c *MainPageController) Code2Session() {

	var resp resonpMsg

	code := c.GetString("code")
	nickname := c.GetString("nickname")
	icon := c.GetString("icon")
	session, role, err := models.AddUserByCode(code, nickname, icon)
	if err != nil {
		resp.Code = errCodeAddUser
		resp.Message = err.Error()
	} else {
		resp.Message = "success"
		resp.Code = 0
		resp.Result.Session = session
		resp.Result.Role = role
	}

	c.Data["json"] = &resp
	c.ServeJSON()
}

// @Title 申请加盟
// @Description 用户通过扫描店铺的URL，申请为美妆师，头像需要先上传
// @Param   session  formData   string  true       ""
// @Param   Tel  	 formData   string  true        "联系电话"
// @Param   Name     formData   string  true        "姓名"
// @Success 200 {object} controllers.result
// @Failure 400
// @Failure 404
// @router /regStaff [post]
func (c *MainPageController) RegisterStore() {

}

func (c *MainPageController) responseResult() {
	type xml struct {
		RetCode string `xml:"return_code"`
		RetMsg  string `xml:"return_msg"`
	}

	response := xml{
		RetCode: "<![CDATA[SUCCESS]]>",
		RetMsg:  "<![CDATA[OK]]>",
	}

	fmt.Println("recv:%v", string(c.Ctx.Input.RequestBody))
	c.Data["xml"] = &response
	c.ServeXML()
}

func (c *MainPageController) PaymentCallback() {

	c.responseResult()

	type xml struct {
		Appid         string `xml:"appid"`
		Mch_id        string `xml:"mch_id"`       //微信支付分配的商户号
		IsSubsCrib    string `xml:"is_subscribe"` //是否关注公众号
		Device_info   string `xml:"device_info"`
		Nonce_str     string `xml:"nonce_str"`
		Sign          string `xml:"sign"`
		Sign_type     string `xml:"sign_type"`
		Body          string `xml:"body"`
		Detail        string `xml:"detail"`
		Attach        string `xml:"attach"`
		Out_trade_no  string `xml:"out_trade_no"` //商户订单号
		Fee_type      string `xml:"fee_type"`
		Total_fee     int32  `xml:"total_fee"`
		Time_end      string `xml:"time_end"`   //20091227091010
		Trade_type    string `xml:"trade_type"` //JSAPI
		Product_id    string `xml:"product_id"` //12235413214070356458058
		OpenId        string `xml:"openid"`
		TransactionId string `xml:"transaction_id"` //微信支付订单号

	}

	res := xml{}

	err := XML.Unmarshal(c.Ctx.Input.RequestBody, &res)
	if err != nil {
		beego.Error("decode failed", err)
		return
	}

	orderId, err := strconv.Atoi(res.Attach)
	if err != nil {
		beego.Error("attach is wrong:", string(c.Ctx.Input.RequestBody))
		return
	}

	err = models.OrderFinishPay(orderId, int(res.Total_fee), res.TransactionId, res.Time_end, res.Out_trade_no)
	if err != nil {
		beego.Error("finish pay failed!")
		return
	}

}
